use Wx 0.15 qw[:allclasses];
use strict;
package wxTreeSelector;

use Wx qw[:everything];
use base qw(Wx::Panel);
use strict;
use Storable;
use wxTreeWindow;
use Scalar::Util qw(blessed);

#Create the panel
sub new {
	my( $self, $parent, $id, $pos, $size, $style, $name ) = @_;
	    
	$parent = undef              unless defined $parent;
	$id     = -1                 unless defined $id;
	$pos    = wxDefaultPosition  unless defined $pos;
	$size   = wxDefaultSize      unless defined $size;
	$name   = ""                 unless defined $name;

	$style = wxDEFAULT_FRAME_STYLE 
		unless defined $style;

	#Create controls
	$self = $self->SUPER::new( $parent, $id, $pos, $size, $style, $name );

	#The tree
	$self->{wxtree} = wxTreeWindow->new($self, -1);
	$self->{wxtree}->set_no_tree_msg("Please select a tree using the button below.\nOr load a saved project from the menu.");
	#Load tree button
	$self->{button_load} = Wx::Button->new($self, -1, "Load Tree");

	#Do the layout
	$self->{sizer} = Wx::BoxSizer->new(wxVERTICAL);
	$self->{sizer}->Add($self->{wxtree}, 1, wxEXPAND, 0);
	$self->{sizer}->Add($self->{button_load},0, wxALIGN_CENTER | wxALIGN_CENTER_VERTICAL);
	$self->SetSizer($self->{sizer});
	$self->{sizer}->Fit($self);
	$self->Layout();
	
	#Register events
	Wx::Event::EVT_BUTTON($self, $self->{button_load}->GetId, \&load_tree);

	return $self;
}

#Set the state
sub set_state {
	my $self = shift;
	$self->{state} = shift;
}

#Load the tree
sub load_tree {
	my $self = shift;

    #Check if the use really wants to add more than one tree
    if (defined $self->{state}->{tree} && !$self->GetParent()->GetParent()->dlg_yesno('Load new tree?',
    	'Loading a new tree will reset your project. Are you sure?')) { return; }

    #Get the file name
    my $filename = $self->GetParent()->GetParent()->dlg_openfile('Select a tree',"Newick files|*");

	unless ($filename) { return; }

	my $treestring = $self->GetParent()->GetParent()->get_filestring($filename,1);

	#Attempt to parse the string
	my $forest = Bio::Phylo::IO->parse(
		-format => 'newick',
		-string => $treestring);

	my $tree = $forest->first;
        
	$self->{state}->{tree} = $tree;
	$self->{wxtree}->set_tree($self->{state}->{tree});
		
	#Get the species list
	my @leaves = @{$tree->get_terminals};
	my @species;
        
	#Get the names of the species
	foreach (@leaves) { push(@species,$_->get_name); }
	@species = sort @species;
	
	#Store species names
	$self->{state}->{species} = \@species;
	$self->{state}->{survival_pd}->set_names(@species);
	$self->{state}->{survival_pd}->set_default_survival;
	$self->{state}->{survival_nap}->set_names(@species);
	$self->{state}->{survival_nap}->set_default_survival;
	$self->{state}->{survival_gnap}->set_names(@species);
	$self->{state}->{survival_gnap}->set_default_survival;
		
	delete $self->{state}->{solutions};
	$self->GetParent()->GetParent()->send_update_signal();
}
	
1;